package cz.fi.muni.pb138.spring2013.dtd2xsd.parse;

import java.util.Scanner;

/**
 * This class contains static methods that can be helpful while parsing input
 * DTD file.
 *
 * @author Valdemar Svabensky
 */
public class Utilities {

    /**
     * Replaces two or more consequent whitespace characters (space, tab, enter)
     * with a single space. Must not affect default values of attributes in DTD.
     *
     * @param input unparsed DTD
     */
    public static StringBuilder removeMultipleWhiteSpace(StringBuilder input) {
        String inputCopy = input.toString();
        try (Scanner scanner = new Scanner(inputCopy)) {
            input = new StringBuilder();
            String matchAllUntilProblematic = ".*?(#FIXED|#REQUIRED|#IMPLIED|NMTOKEN) ";
            String beforeProblematic = scanner.findInLine(matchAllUntilProblematic);
            if (beforeProblematic == null) {
                input.append(inputCopy.replaceAll("\\s+", " "));
            }
            else {
                do {
                    input.append(beforeProblematic.replaceAll("\\s+", " "));
                    String afterCurrentSection = scanner.findInLine(".*?(?<=\")([^\"]*)");
                    if (afterCurrentSection != null) {
                        input.append(afterCurrentSection);
                    }
                } while ((beforeProblematic = scanner.findInLine(matchAllUntilProblematic)) != null);
                
                String end = scanner.findInLine(".*");
                if (end != null) {
                    input.append(end.replaceAll("\\s+?", " "));
                }
            }
            return input;
        }
    }
}
